﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;

public partial class BookingManage_PendingList : BasePage
{
    IBNBookingHandler bookingManager = new BNBookingHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    string language = "";
    private bool isCpmRole2 = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        ISystemHandler sysManage = new SystemHandler();
        language = Thread.CurrentThread.CurrentUICulture.ToString().ToLower();

        // is company user?
        isCpmRole2 = sysManage.IsCompanyRoles2();
        if (!"0".Equals(Session["LoginUserClientID"].ToString()) && !isCpmRole2)
        {
            Response.Redirect("PendingList.aspx");
        }

        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1046"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    //判断用户有没有Send Booking权限
                    if (strPermission.Contains("1047"))
                    {
                        btnSave.Visible = true;
                    }
                    else
                    {
                        btnSave.Visible = false;
                    }
                }

               // CheckPagePermission();//判断当前用户有没有添加删除更新的权限

            }
           
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "asc";
            dataBind();

            #region 绑定托运人

            //绑定托运人
            DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
            lstShipper.DataSource = dt;

            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                lstShipper.DataTextField = "ENGShortName";
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                lstShipper.DataTextField = "HKShortName";
            }
            else
            {
                lstShipper.DataTextField = "CNShortName";
            }
            lstShipper.DataValueField = "PKID";
            lstShipper.DataBind();

            #endregion

            fillFactory();
        }
    }

    private void fillFactory()
    {
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        lstFactory.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstFactory.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstFactory.DataTextField = "HKShortName";
        }
        else
        {
            lstFactory.DataTextField = "CNShortName";
        }
        lstFactory.DataValueField = "PKID";
        lstFactory.DataBind();
    }


    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        string column;
        string value;
        sqlstr = "";

        if (ViewState["ColumnValue"] != null)
        {
            column = ViewState["ColumnName"].ToString();
            value = ViewState["ColumnValue"].ToString();
            list.Add(new SqlParameter("@ColumnValue", value));
            if ("Whouse".Equals(column))
            {
                sqlstr += @" and ((whouse.CNShortName LIKE @ColumnValue) 
                                    or (whouse.ENGShortName like @ColumnValue)
                                    or (whouse.HKShortName like @ColumnValue))";
            }
            else if ("Vendor".Equals(column))
            {
                sqlstr += @" and ((vendor.CNShortName LIKE @ColumnValue) 
                                    or (vendor.ENGShortName like @ColumnValue)
                                    or (vendor.HKShortName like @ColumnValue))";
            }
        }

        if (ViewState["Shipper"] != null)
        {
            sqlstr += " and (shipper.PKID in (" + ViewState["Shipper"] + ")) ";
        }

        if (ViewState["Factory"] != null)
        {
            sqlstr += " and (vendor.PKID in (" + ViewState["Factory"] + "))";
        }

        if (ViewState["Between"] != null && ViewState["To"] != null)
        {
            column = ViewState["ColumnName2"].ToString();
            value = ViewState["Between"].ToString();
            string value2 = ViewState["To"].ToString();
            list.Add(new SqlParameter("@From", value));
            list.Add(new SqlParameter("@To", value2));

            if ("WinStart".Equals(column))
            {
                sqlstr += " and (dtl.WinStart between @From and @To)";
            }
            else if ("WinClose".Equals(column))
            {
                sqlstr += " and (dtl.WinClose between @From and @To)";
            }
        }
        else if (ViewState["Between"] != null && ViewState["To"] == null)
        {
            column = ViewState["ColumnName2"].ToString();
            value = ViewState["Between"].ToString();
            list.Add(new SqlParameter("@From", value));

            if ("WinStart".Equals(column))
            {
                sqlstr += " and (dtl.WinStart >= @From)";
            }
            else if ("WinClose".Equals(column))
            {
                sqlstr += " and (dtl.WinClose >= @From)";
            }
        }
        else if (ViewState["Between"] == null && ViewState["To"] != null)
        {
            column = ViewState["ColumnName2"].ToString();
            value = ViewState["To"].ToString();
            list.Add(new SqlParameter("@To", value));

            if ("WinStart".Equals(column))
            {
                sqlstr += " and (dtl.WinStart <= @To)";
            }
            else if ("WinClose".Equals(column))
            {
                sqlstr += " and (dtl.WinClose <= @To)";
            }
        }
        parms = list.ToArray();
    }

    private void dataBind()
    {
        DataTable dt = getSearchData();
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvPendingList.DataSource = view;
        gvPendingList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private DataTable getSearchData()
    {
        string sqlStr = @"SELECT booking.PKID as BID, dtl.*,whouse.CNShortName as Whouse, whouse.HKShortName as HKWhouse, 
                            whouse.ENGShortName as ENGWhouse, shipper.CNShortName as Shipper,
                            shipper.HKShortName as HKShipper, shipper.ENGShortName as ENGShipper,
                            vendor.CNShortName as Vendor, vendor.HKShortName as HKVendor, vendor.ENGShortName as ENGVendor,
                            vendor.PKID as fid
                        FROM BN_Booking booking inner join 
                            BN_BookingDtl dtl on booking.PKID = dtl.BookingID LEFT JOIN
                            Sy_Client whouse ON dtl.WhouseID = whouse.PKID LEFT JOIN
                            Sy_Client shipper ON dtl.ShipperID = shipper.PKID LEFT JOIN
                            Sy_Client vendor ON booking.VendorID = vendor.PKID
                        WHERE (dtl.JobDate IS NULL OR dtl.JobDate = '') ";
        if (isCpmRole2)
        {
            sqlStr += " and (booking.BookingUser in (select UserID from Users where ClientID = " + Session["LoginUserClientID"].ToString() + ")) ";
        }

        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        return bookingManager.GetList(sqlStr, parms);
    }

    protected void gvPendingList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvPendingList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void gvPendingList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dataBind();

    }
    protected void gvPendingList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        buildSearchCondition();
        dataBind();

        setFactoryByCondition();
    }

    private void buildSearchCondition()
    {
        if (lstSelShipper.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                item += lstSelShipper.Items[i].Value + ",";
            }
            ViewState["Shipper"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Shipper"] = null;
        }
        if (lstSelFactory.Items.Count > 0)
        {
            string item = string.Empty;
            for (int i = 0; i < lstSelFactory.Items.Count; i++)
            {
                item += lstSelFactory.Items[i].Value + ",";
            }
            ViewState["Factory"] = item.Substring(0, item.Length - 1);
        }
        else
        {
            ViewState["Factory"] = null;
        }
        if (txtColumnValue.Text != string.Empty)
        {
            ViewState["ColumnValue"] = txtColumnValue.Text.Trim();
            ViewState["ColumnName"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["ColumnName"] = null;
            ViewState["ColumnValue"] = null;
        }

        if (txtBetween.Text != string.Empty && txtTo.Text != string.Empty)
        {
            ViewState["ColumnName2"] = ddlColumnName2.SelectedValue;
            ViewState["Between"] = txtBetween.Text.Trim() + " 00:00:00";
            ViewState["To"] = txtTo.Text.Trim() + " 23:59:59";
        }
        else if (txtBetween.Text != string.Empty && txtTo.Text == string.Empty)
        {
            ViewState["ColumnName2"] = ddlColumnName2.SelectedValue;
            ViewState["Between"] = txtBetween.Text.Trim() + " 00:00:00";
            ViewState["To"] = null;
        }
        else if (txtBetween.Text == string.Empty && txtTo.Text != string.Empty)
        {
            ViewState["ColumnName2"] = ddlColumnName2.SelectedValue;
            ViewState["Between"] = null;
            ViewState["To"] = txtTo.Text.Trim() + " 23:59:59";
        }
        else
        {
            ViewState["ColumnName2"] = null;
            ViewState["Between"] = null;
            ViewState["To"] = null;
        }
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvPendingList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void gvPendingList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblShipper = (Label)e.Row.FindControl("lblShipper");
            Label lblHKShipper = (Label)e.Row.FindControl("lblHKShipper");
            Label lblENGShipper = (Label)e.Row.FindControl("lblENGShipper");

            Label lblWhouse = (Label)e.Row.FindControl("lblWhouse");
            Label lblHKWhouse = (Label)e.Row.FindControl("lblHKWhouse");
            Label lblENGWhouse = (Label)e.Row.FindControl("lblENGWhouse");

            Label lblVendor = (Label)e.Row.FindControl("lblVendor");
            Label lblHKVendor = (Label)e.Row.FindControl("lblHKVendor");
            Label lblENGVendor = (Label)e.Row.FindControl("lblENGVendor");

            if ("en".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = true;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = true;

                lblVendor.Visible = false;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = true;
            }
            else if ("zh-hk".Equals(language))
            {
                lblShipper.Visible = false;
                lblHKShipper.Visible = true;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = false;
                lblHKWhouse.Visible = true;
                lblENGWhouse.Visible = false;

                lblVendor.Visible = false;
                lblHKVendor.Visible = true;
                lblENGVendor.Visible = false;
            }
            else
            {
                lblShipper.Visible = true;
                lblHKShipper.Visible = false;
                lblENGShipper.Visible = false;

                lblWhouse.Visible = true;
                lblHKWhouse.Visible = false;
                lblENGWhouse.Visible = false;

                lblVendor.Visible = true;
                lblHKVendor.Visible = false;
                lblENGVendor.Visible = false;
            }
        }
    }


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvPendingList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvPendingList.PageCount)
            {
                this.gvPendingList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            bool isDateTime = false;
            Regex reg = new Regex("((1[89]\\d{2})|([2-8]\\d{3}))[-](([1][012])|(0{1}[1-9]))[-]((3[01])|([12]\\d)|(0{1}[1-9]))");
            isDateTime = reg.IsMatch(txtNewJobDate.Text.Trim());
            reg = new Regex("(([0][0-9])|([1][0-9])|([2][0-3]))([0-5][0-9])");
            string h = txtNewJobDateH.Text.Trim();
            h = h.Replace(":", "");
            isDateTime = isDateTime && reg.IsMatch(h);

            if (isDateTime)
            {
                string jobDate = txtNewJobDate.Text.Trim() + StringUtil.GetTime(txtNewJobDateH.Text.Trim());
                string[] dtlIds = Request["chkSelected"].ToString().Split(',');
                string userName = Session["UserName"].ToString();
                object userId = Session["UserID"];
                foreach (string dtlId in dtlIds)
                {
                    string sql = "update bn_bookingnotedtl set status=@Status where pkid=(select bookingnotedtlid from bn_bookingdtl where pkid=@PKID)";
                    SqlParameter[] parms = new SqlParameter[2];
                    parms[0] = new SqlParameter("@Status", HK2009.Common.Enums.BookingNoteDtlStatus.BOOKING.ToString("d"));
                    parms[1] = new SqlParameter("@PKID", dtlId);
                    bookingManager.UpdateBookingStatus(sql, parms);
                    if (!bookingManager.UpdateDetail(int.Parse(dtlId), jobDate, userName, userId, true))
                    {
                        Jscript.AlertInAjax(Resources.Messages.UpdateFailed, UpdatePanel1);
                        return;
                    }
                }
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongDateTimeFormat, UpdatePanel1);
            }
            dataBind();
        }
    }


    protected void btnAddSShipper_Click(object sender, EventArgs e)
    {
        if (lstShipper.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstShipper.Items.Count; i++)
            {
                bool issel = false;
                if (lstShipper.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelShipper.Items.Count; j++)
                    {
                        if (lstShipper.Items[i].Value == lstSelShipper.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstShipper.Items[i].Text;
                        item.Value = lstShipper.Items[i].Value;
                        lstSelShipper.Items.Add(item);
                    }
                }
            }
            setFactoryByCondition();
        }
        else
        {

        }

    }
    protected void btnDeleteSShipper_Click(object sender, EventArgs e)
    {
        if (lstSelShipper.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelShipper.Items.Count; i++)
            {
                if (!lstSelShipper.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelShipper.Items[i].Text, lstSelShipper.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelShipper.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelShipper.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelShipper.Items.Clear();
            }

            setFactoryByCondition();
        }
    }

    protected void btnAddSFactory_Click(object sender, EventArgs e)
    {
        if (lstFactory.SelectedValue != string.Empty)
        {
            for (int i = 0; i < lstFactory.Items.Count; i++)
            {
                bool issel = false;
                if (lstFactory.Items[i].Selected)
                {
                    for (int j = 0; j < lstSelFactory.Items.Count; j++)
                    {
                        if (lstFactory.Items[i].Value == lstSelFactory.Items[j].Value)
                        {
                            issel = true;
                            break;
                        }
                    }

                    if (!issel)
                    {
                        ListItem item = new ListItem();
                        item.Text = lstFactory.Items[i].Text;
                        item.Value = lstFactory.Items[i].Value;
                        lstSelFactory.Items.Add(item);
                    }
                }
            }

            setFactoryByCondition();
        }
        else
        {

        }

    }
    protected void btnDeleteFactory_Click(object sender, EventArgs e)
    {
        if (lstSelFactory.Items.Count > 0)
        {
            ListItemCollection lstColl = new ListItemCollection();
            for (int i = 0; i < lstSelFactory.Items.Count; i++)
            {
                if (!lstSelFactory.Items[i].Selected)
                {
                    ListItem item = new ListItem(lstSelFactory.Items[i].Text, lstSelFactory.Items[i].Value);
                    lstColl.Add(item);
                }
            }
            if (lstColl != null && lstColl.Count > 0)
            {
                lstSelFactory.Items.Clear();
                for (int j = 0; j < lstColl.Count; j++)
                {
                    lstSelFactory.Items.Add(lstColl[j]);
                }
            }
            else
            {
                lstSelFactory.Items.Clear();
            }

            setFactoryByCondition();
        }

    }

    private void setFactoryByCondition()
    {
        buildSearchCondition();
        DataTable dt = getSearchData();

        DataTable dtFactory = dt.Clone();
        dtFactory.Rows.Clear();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            bool isExists = false;
            for (int j = 0; j < dtFactory.Rows.Count; j++)
            {
                if (dt.Rows[i]["fid"].ToString().Equals(dtFactory.Rows[j]["fid"].ToString()))
                {
                    isExists = true;
                    break;
                }
            }

            if (!isExists)
            {
                dtFactory.ImportRow(dt.Rows[i]);
            }
        }

        lstFactory.DataSource = null;
        lstFactory.DataBind();

        lstFactory.DataSource = dtFactory;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            lstFactory.DataTextField = "ENGVendor";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            lstFactory.DataTextField = "HKVendor";
        }
        else
        {
            lstFactory.DataTextField = "Vendor";
        }
        lstFactory.DataValueField = "fid";
        lstFactory.Items.Clear();
        lstFactory.DataBind();

    }

}
